package com.wkh.web.manager;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author wangkehua
 * 多级缓存操作管理
 */
@Component
public class CacheManager {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    //本地缓存Caffeine构造器
    private Cache<String, Object> localCache = Caffeine.newBuilder()
            .expireAfterWrite(100, TimeUnit.MINUTES)
            .maximumSize(10000)
            .build();

    public void put(String key, Object value){
        localCache.put(key,value);
        //缓存进reids
        redisTemplate.opsForValue().set(key,value,30, TimeUnit.MINUTES);
    }

    /**
     * 读缓存
     * @param key
     * @return
     */
    public Object get(String key){
        //查找一个缓存元素，没有则返回null
        //先从本地缓存中获取数据
        Object value = localCache.getIfPresent(key);
        //判断本地缓存中是否存在
        if (value != null){
            return value;
        }
        //本地缓存中不存在,从redis中获取
        value = redisTemplate.opsForValue().get(key);
        if (value != null){
            //将redis中的数据存入本地缓存
            localCache.put(key,value);
        }
        return value;
    }
    public void delete(String key){
        localCache.invalidate(key);
        //清除redis中的数据
        redisTemplate.delete(key);
    }
}
